import {http} from 'share/common/api.js'
import * as types from './mutation-types'
import {isValidStart, readableSize, readableTime} from 'libs/utils.js'

function makeFontColorShow(list) {
  list.forEach(function(item, index, array) {
    item.fontColorShow = '<div style="border-style:solid;border-color:#000;border-width:1px;background-color:' + item.fontColor + ';width:40px;height:20px;margin:0;margin-left:auto;margin-right:auto"></div>'
  })
}
export function getCodecInfo({dispatch}, serverIp, listName) {
  setHostname(serverIp)
  multimediaApi.getItems(listName).then(function(res){
    if (listName === 'subtitleListOfWindow') {
      makeFontColorShow(res.data.data.subtitleListOfWindow)
      dispatch(types.GET_CODEC_INFO, res.data.data.subtitleListOfWindow)
    } else {
      makeFontColorShow(res.data.data.subtitleListOfVpOut)
      dispatch(types.GET_CODEC_INFO, res.data.data.subtitleListOfVpOut)
    }
  })
}

export function getRecordFiles({dispatch}, ipaddr, url) {
  var lists = []
  http("http://" + ipaddr + ":6080", url, 'GET').then(function(res) {
    if(res && res.data && res.data.code === 0) {
      var startIndex = 1
      var records = res.data.data.records
      lists.splice(0, lists.length)
      _.each(records, function(item, index, list) {
        item._id = startIndex++
        item.sizeR = readableSize(item.size)
        item.durationR = readableTime(item.duration)
        var starttime = new Date(Date.parse(item.starttime))
        item.starttimeR = starttime.toLocaleString()
        item.playUrlLink = '<a href="tzdb://' + item.playUrl.replace(/rtsp\:\/\/\{ip\}/, ipaddr) + '" >点播</a>'
        item.folderLink = 'file://///' + ipaddr+ '/data/MediaRecord/' + item.roomName + item.playUrl.substr(item.playUrl.lastIndexOf("/"))
        lists.splice(lists.length, 0, item) 
      })
      dispatch(types.GET_RECORDED_FILES, lists)
    }
  })
}

export function getRecordFilesLink({dispatch}, ipaddr, url) {
  var dlLists = []
  http("http://" + ipaddr + ":6080", url, 'GET').then(function(res) {
    if(res && res.data && res.data.code === 0) {
      var startIndex = 1
      var recordfiles = res.data.data.recordfiles
      _.each(recordfiles, function(item, index, list) {
        item._id = startIndex++
        item.downloadLink = '<a href="http://' + ipaddr + ':6080/api/storage/file?type=AP&path=' + item.fileName + '">' + item.fileName.substr(item.fileName.lastIndexOf('/') + 1) + '</a>'
        dlLists.splice(dlLists.length, 0, item)
      }.bind(this), this)
      dispatch(types.GET_RECORDED_FILES_LINK, dlLists)
    }
  })
}